<template>
  <div class="work-container">
    <van-panel :title="oddjobId?'修改零工报工单':'添加零工报工'">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :disabled="!oddjobUser"
        label-width="80px"
      >
        <el-form-item
          label="出工方式"
          prop="wmId"
        >
          <el-select
            v-model="form.wmId"
            @change="handleGetwmPay"
            placeholder="请选择"
          >
            <el-option
              v-for="item in wmOptions"
              :key="item.wmId"
              :label="item.wmName"
              :value="item.wmId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="计薪"
          prop="wmPay"
        >
          <el-input
            v-model="form.wmPay"
            :disabled="true"
            placeholder="请输入计薪"
          >
            <template slot="append">元/{{ sourceWmUnitFormat(form.wmUnit) }}</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="所属模块"
          prop="moduleId"
        >
          <el-select
            v-model="form.moduleId"
            :disabled="true"
            filterable
            @change="handleChangeModule"
            placeholder="请选择所属模块"
          >
            <el-option
              v-for="item in moduleOptions"
              :key="item.moduleId"
              :label="item.moduleName"
              :value="item.moduleId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="所属车间"
          prop="workshopId"
        >
          <el-select
            v-model="form.workshopId"
            filterable
            @change="handleChangeWorkshop"
            placeholder="请选择所属车间"
          >
            <el-option
              v-for="item in workshopOptions"
              :key="item.workshopId"
              :label="item.workshopName"
              :value="item.workshopId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="大工序"
          prop="gprocessId"
        >
          <el-select
            v-model="form.gprocessId"
            filterable
            @change="handleChangeProcess"
            placeholder="请选择大工序"
          >
            <el-option
              v-for="item in gprocessOptions"
              :key="item.gprocessId"
              :label="item.gprocessName"
              :value="item.gprocessId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="小工序ID"
          prop="processId"
        >
          <el-select
            v-model="form.processId"
            filterable
            placeholder="请选择小工序"
          >
            <el-option
              v-for="item in processOptions"
              :key="item.processId"
              :label="item.processName"
              :value="item.processId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="实际生产"
          prop="rworkActual"
        >
          <el-input
            v-model="form.rworkActual"
            class="def-input-number"
            type="number"
            placeholder="请输入实际生产"
          />
        </el-form-item>
        <el-form-item
          label="开始时间"
          prop="oddjobStart"
        >
          <div class="flex-box">
            <el-date-picker
              clearable
              style="width:100%"
              v-model="form.oddjobStart"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              default-time="12:00:00"
              placeholder="请选择开始时间"
              :picker-options="pickerOptions"
              @change="handleCompareTime"
            >
            </el-date-picker>
            <el-button
              type="text"
              @click="setTime(1)"
            >此刻</el-button>
          </div>
        </el-form-item>
        <el-form-item
          label="结束时间"
          prop="oddjobEnd"
        >
          <div class="flex-box">
            <el-date-picker
              clearable
              style="width:100%"
              v-model="form.oddjobEnd"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择结束时间"
              :picker-options="pickerOptions"
              @change="handleCompareTime"
            >
            </el-date-picker>
            <el-button
              type="text"
              @click="setTime(2)"
            >此刻</el-button>
          </div>
        </el-form-item>

        <el-form-item
          label="时长"
          prop="oddjobDuration"
        >
          <el-input
            v-model="form.oddjobDuration"
            placeholder="请输入时长"
          />
        </el-form-item>
      </el-form>
    </van-panel>
    <van-panel title="零工操作人">
      <van-button
        :disabled="!oddjobUser"
        size="small"
        type="info"
        @click="addPeople"
      >+添加操作人</van-button>
      <div
        v-for="(item, index) in slOddjobOmemberList"
        :key="index"
        class="user-panel"
      >
        <van-icon
          class="close-btn"
          name="close"
          size="20"
          color="#ff4949"
          @click="handleDeleteSlOddjobOmember(index)"
        />
        <van-cell-group>
          <van-field
            label-width="5em"
            label="操作人"
            :value="item.omemberNick"
            readonly
          />
          <van-field
            label-width="5em"
            label="职级"
            :value="item.levelName"
            readonly
          />
          <van-field
            label-width="5em"
            label="计薪方式"
            :value="item.ssmName"
            readonly
          />
        </van-cell-group>
      </div>
      <van-empty
        v-if="!slOddjobOmemberList.length"
        image-size="120px"
        description="请选择操作人"
      />
    </van-panel>
    <div class="fixed-bar">
      <van-button
        type="default"
        round
        @click="goback"
      >返回</van-button>
      <van-button
        :disabled="!oddjobUser"
        type="info"
        round
        @click="submitForm"
      >保存</van-button>
    </div>

    <van-popup
      v-model="showFlag"
      round
      position="bottom"
      @closed="popupClosed"
    >
      <van-nav-bar
        title="请选择操作人"
        left-text="取消"
        right-text="确认"
        @click-left="onClickLeft"
        @click-right="onClickRight"
      />
      <van-search
        v-model="userQueryParams.nickName"
        placeholder="请输入中文昵称"
        @search="onSearch"
        @clear="onClear"
      />
      <div style="height: 80vh; overflow: auto;">
        <van-checkbox-group
          v-model="result"
          ref="checkboxGroup"
        >
          <van-cell-group>
            <van-cell
              v-for="(item, index) in userList"
              clickable
              :key="item.userId"
              :title="`${item.userName} - ${item.nickName}`"
              @click="toggle(index)"
            >
              <template #default>
                <span class="dept">{{item.dept?item.dept.deptName:''}}</span>
              </template>
              <template #right-icon>
                <van-checkbox
                  :name="item"
                  ref="checkboxes"
                />
              </template>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </div>
      <!-- <van-cascader v-model="deptValue" title="请选择部门" :options="deptOptions" @close="showFlag = false" @finish="onFinish" /> -->
    </van-popup>
  </div>
</template>

<script>
import { Notify } from 'vant';
import { Dialog } from 'vant';
import { getOddjob, addOddjob, updateOddjob, getOddjobOptions, isUniqueJobUser } from "@/api/sl/oddjob";
import { formatOnlyDate } from '@/utils/index'
import { rworkUserBase, getRworkOptions, getOftenMember } from "@/api/sl/rwork";
import { getProcessListByGprocessId } from "@/api/sl/process";
import { getWorkshopListByModuleId } from "@/api/sl/workshop";
import { getGprocessListByWorkshopId } from "@/api/sl/gprocess";
import { listUserSel } from "@/api/system/user";

export default {
  name: "h5OddjobEdit",
  components: {
    [Notify.Component.name]: Notify.Component,
    [Dialog.Component.name]: Dialog.Component,
  },
  dicts: ['sl_rwork_class', 'sl_wm_unit'],
  data() {
    let watermarkContentVaild = (rule, value, callback) => {
      if (value == null || value === "") {
        callback();
      } else {
        let length = value.length
        if (length > 7) {
          callback(new Error("输入不能超过7位"))
        } else {
          callback();
        }
      }
    }
    return {
      oddjobId: undefined,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        wmPay: [
          { required: true, message: "计薪不能为空", trigger: "blur" }
        ],
        wmId: [
          { required: true, message: "零工/小时工不能为空", trigger: "blur" },
          { validator: watermarkContentVaild, trigger: 'blur' }
        ]
      },
      oddjobUser: null,
      oddjobDate: formatOnlyDate(new Date()),
      moduleOptions: [],
      wmOptions: [],
      // 操作人表格数据
      slOddjobOmemberList: [],
      //限制时间选择范围
      pickerOptions: {
        disabledDate(date) {
          let ts = date.getTime()
          let now = Date.now()
          let limitDays = 2 * 24 * 60 * 60 * 1000 // 2天的毫秒数
          if (ts <= now && ts >= now - limitDays) {
            return false;
          } else {
            return true;
          }
        }
      },
      //模块
      moduleOptions: [],
      //车间
      workshopOptions: [],
      //大工序
      gprocessOptions: [],
      //小工序
      processOptions: [],
      userQueryParams: {
        pageNum: 1,
        pageSize: 1000,
        nickName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      userList: [],
      showFlag: false,
      searchValue: '',
      result: [],
      from: undefined
    }
  },
  computed: {
  },
  created() {
    //获取当前报工人信息
    this.getRworkUserBase(this.$store.state.user.name);
    this.getUserList();
  },
  methods: {
    init() {
      this.oddjobId = this.$route.query.oddjobId;
      this.from = this.$route.query.from;
      console.log(this.oddjobId);
      this.reset();
      this.form.moduleId = this.oddjobUser.moduleId;
      if (this.oddjobId) {
        getOddjob(this.oddjobId).then(response => {
          this.form = response.data;
          this.wmOptions = response.wms;
          this.moduleOptions = response.modules;
          this.slOddjobOmemberList = response.data.slOddjobOmemberList;
        });
      }
      const query = {
        moduleId: this.oddjobUser.moduleId,
        workshopId: this.oddjobUser.workshopId,
        leaderUser: this.oddjobUser.leaderUser
      }
      getOddjobOptions(query).then(response => {
        this.wmOptions = response.wms;
      });
      getRworkOptions(query).then(response => {
        this.moduleOptions = response.modules
        this.workshopOptions = response.workshops
        this.gprocessOptions = response.gprocesss
      });
    },
    //获取报工人模块车间信息
    getRworkUserBase(userName) {
      if (userName != null && userName != "") {
        rworkUserBase(userName).then(response => {
          if (response.data != null) {
            this.oddjobUser = response.data;
            this.init();
          } else {
            Notify({ type: 'danger', message: '您没有报工权限，请联系管理员。' });
          }
        });
      } else {
        Notify({ type: 'danger', message: '未获取到报工人信息。' });
      }
    },

    // 表单重置
    reset() {
      this.form = {
        oddjobId: null,
        oddjobDate: null,
        moduleId: null,
        workshopId: null,
        gprocessId: null,
        processId: null,
        rworkActual: null,
        oddjobYear: null,
        oddjobMonth: null,
        oddjobDay: null,
        isApproved: null,
        leaderUser: null,
        oddjobStart: null,
        oddjobEnd: null,
        oddjobDuration: null,
        wmPay: null,
        estimatePay: null,
        oddjobUser: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        wmId: null,
        oddjobBz: null,
        wmUnit: null,
        rfworkId: null,
        oddjobDm: null
      };
      this.slOddjobOmemberList = [];
      this.resetForm("form");
    },
    //模块变更查询车间
    handleChangeModule(value) {
      //清空车间
      this.form.workshopId = null;
      this.workshopOptions = [];
      //清空大工序
      this.form.gprocessId = null;
      this.gprocessOptions = [];
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getWorkshopListByModuleId(value).then(response => {
        this.workshopOptions = response.data;
      });
    },
    //车间变更查询大工序
    handleChangeWorkshop(value) {
      //清空大工序
      this.form.gprocessId = null;
      this.gprocessOptions = [];
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getGprocessListByWorkshopId(value).then(response => {
        this.gprocessOptions = response.data;
      });
    },
    //大工序变更查询小工序
    handleChangeProcess(value) {
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getProcessListByGprocessId(value).then(response => {
        this.processOptions = response.data;
      });
    },
    //获取出工方式计价
    handleGetwmPay(value) {
      for (let i = 0; i < this.wmOptions.length; i++) {
        if (this.wmOptions[i].wmId === value) {
          this.form.wmPay = this.wmOptions[i].wmPay;
          this.form.wmUnit = this.wmOptions[i].wmUnit;
          //this.handleCountPay()
          break;
        }
      }
    },
    // 计价单位字典翻译
    sourceWmUnitFormat(unit) {
      if (unit != null) {
        return this.selectDictLabel(this.dict.type.sl_wm_unit, unit);
      }
    },
    //比较时间
    handleCompareTime() {
      if (this.form.oddjobStart && this.form.oddjobEnd) {
        let difference = new Date(this.form.oddjobEnd) - new Date(this.form.oddjobStart);
        this.form.oddjobDuration = (difference / 3600000).toFixed(2)
        //this.handleCountPay()
      } else {
        this.form.oddjobDuration = null;
      }
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUserSel(this.userQueryParams).then(response => {
        this.userList = response.rows;
        getOftenMember(this.$store.state.user.name).then(response => {
          const valuesToBringFront = response.data || [];
          if (valuesToBringFront.length) {
            this.userList.sort((a, b) => {
              if (valuesToBringFront.includes(a.userName) && !valuesToBringFront.includes(b.userName)) {
                return -1;
              } else if (!valuesToBringFront.includes(a.userName) && valuesToBringFront.includes(b.userName)) {
                return 1;
              }
              return 0;
            });
          }
        });
        this.loading = false;
      }
      );
    },
    popupClosed() {
      this.$refs.checkboxGroup.toggleAll(false);
    },
    onClickLeft() {
      console.log('取消');
      this.showFlag = false;
    },
    onClickRight() {
      this.showFlag = false;
      console.log(this.result);
      if (this.result && this.result.length) {
        this.userSelected(this.result);
      }
    },
    userSelected(rows) {
      if (rows != null) {
        rows.forEach(user => {
          //console.log(user)
          let obj = {};
          obj.omemberUser = user.userName;
          obj.omemberNick = user.nickName;
          obj.levelId = user.levelId;
          obj.ssmId = user.ssmId;
          obj.levelName = user.level.levelName;
          obj.ssmName = user.ssm.ssmName;

          if (isUniqueJobUser(this.slOddjobOmemberList, obj)) {
            this.slOddjobOmemberList.push(obj);
          }
        })
      }
    },
    handleDeleteSlOddjobOmember(index) {
      this.slOddjobOmemberList.splice(index, 1);
    },
    addPeople() {
      this.showFlag = true;
    },
    onSearch() {
      this.getUserList();
    },
    onClear() {
      this.userQueryParams.nickName = undefined;
      this.getUserList();
    },
    toggle(index) {
      this.$refs.checkboxes[index].toggle();
    },
    goback() {
      this.$router.go(-1);
    },
    setTime(num) {
      if (num === 1) {
        this.form.oddjobStart = this.parseTime(new Date());
      } else if (num === 2) {
        this.form.oddjobEnd = this.parseTime(new Date());
      }
      this.handleCompareTime();
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.$refs["form"]);
      this.$refs["form"].validate(valid => {
        if (valid) {

          if (this.slOddjobOmemberList.length == 0) {
            Notify({ type: 'danger', message: '操作人不能为空。' });
            return;
          }
          //直属领导
          this.form.leaderUser = this.oddjobUser.leaderUser;
          this.form.slOddjobOmemberList = this.slOddjobOmemberList;
          if (this.form.oddjobId != null) {
            if (this.from === 'history') {
              Dialog.confirm({
                title: '提示',
                message: '是否确认重新提交审批？',
              }).then(() => {
                updateOddjob(this.form).then(response => {
                  Notify({ type: 'success', message: '重新提交成功' });
                  this.$router.go(-1);
                });
              }).catch(() => {
                // on cancel
              });
            } else {
              updateOddjob(this.form).then(response => {
                Notify({ type: 'success', message: '修改成功' });
                this.$router.go(-1);
              });
            }

          } else {
            addOddjob(this.form).then(response => {
              Notify({ type: 'success', message: '新增成功' });
              this.$router.go(-1);
            });
          }
        }
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.work-container {
  padding-bottom: 80px;
  &::v-deep {
    .van-cell-group {
      & + .van-cell-group {
        margin-top: 10px;
      }
    }
    .van-panel__header {
      font-size: 16px;
      font-weight: bold;
      span {
        &::before {
          content: '□';
          margin-right: 6px;
        }
      }
    }
    .van-panel__content {
      padding: 15px;
    }
    .el-select,
    .el-autocomplete {
      display: block;
    }
    .el-input-number {
      width: 100%;
    }
  }
}
.flex-box {
  display: flex;
  &::v-deep {
    .el-input {
      flex: 1;
    }
    .el-button {
      margin-left: 5px;
    }
  }
}
.fixed-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  padding: 10px 15px;
  text-align: right;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 0 10px 5px rgba(51, 51, 51, 0.04);
  button {
    width: 48%;
  }
}
.dept {
  margin-right: 10px;
  font-size: 12px;
}
.user-panel {
  position: relative;
  padding: 5px;
  background-color: #ebedf0;
  margin-top: 5px;
  .close-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1;
  }
}
@media (max-width: 550px) {
}
</style>
